package utils

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
)

type UserClaims struct {
	Identity string `json:"identity"`
	Email    string `json:"email"`
	jwt.StandardClaims
}

var myKey = []byte("IMChat")

func GenerateToken(identity, email string) (string, error) {
	//hex, err := primitive.ObjectIDFromHex(identity)
	//if err != nil {
	//	return "", err
	//}
	uc := &UserClaims{

		Identity:       identity,
		Email:          email,
		StandardClaims: jwt.StandardClaims{}}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, uc)
	tokenString, err := token.SignedString([]byte(myKey))
	if err != nil {
		return "", err
	}
	return tokenString, nil
}
func ParseToken(token string) (*UserClaims, error) {
	userClaim := new(UserClaims)
	claims, err := jwt.ParseWithClaims(token, userClaim, func(token *jwt.Token) (interface{}, error) {
		return []byte(myKey), nil
	})
	if err != nil {
		return nil, err
	}
	if !claims.Valid {
		return nil, fmt.Errorf("parse Token Error : " + err.Error())
	}
	return userClaim, nil
}
